package com.yb.bluetooth

import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.ArrayAdapter
import android.widget.EditText
import android.widget.ListView
import com.yb.bluetooth.entity.BtItem
import com.yb.bluetooth.entity.BtMessage
import com.yb.bluetooth.normal.BtUtils
import com.yb.bluetooth.util.LiveBus
import com.yb.bluetooth.util.TempDataUtils
import com.blankj.utilcode.util.ToastUtils

class OtherActivity : AppCompatActivity() {

    private val lv by lazy(LazyThreadSafetyMode.NONE) {  findViewById<ListView>(R.id.lv)  }
    private val editMsg by lazy(LazyThreadSafetyMode.NONE) {  findViewById<EditText>(R.id.edit_msg)  }

    private val item: BtItem? by lazy {
        intent.getParcelableExtra(MainActivity.DATA)
    }

    private val mOtherList = mutableListOf<String>()

    private val mListAdapter: ArrayAdapter<String> by lazy {
        ArrayAdapter(this@OtherActivity, android.R.layout.simple_expandable_list_item_1, mOtherList).apply { lv.adapter = this }
    }

    private val message: String get() = editMsg.text.toString()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_other)
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
        val name = item?.deviceName ?: item!!.deviceAddress
        val tempData = TempDataUtils.getTempData(item!!.deviceAddress)
        mListAdapter.addAll(tempData)
        title = name
        LiveBus.observe(this) { bt: BtMessage ->
            if (bt.name != name) return@observe
            if (bt.message == MainActivity.DISCONNECT) {
                ToastUtils.showShort("已断开")
                finish()
            } else {
                mListAdapter.add("${name}：${bt.message}")
            }
        }
    }

    fun onClick(view: View) {
        BtUtils.sendMessage(item!!.deviceAddress, message) {
            if (it) {
                mListAdapter.add("本机：$message")
                editMsg.setText("")
            } else {
                ToastUtils.showShort("发送失败")
            }
        }
    }

    override fun onBackPressed() {
        TempDataUtils.putTempData(item!!.deviceAddress, mOtherList)
        setResult(Activity.RESULT_OK, Intent())
        super.onBackPressed()
    }
}